package com.zhituanbox.extensions.core.validator;

import org.hibernate.validator.resourceloading.DelegatingResourceBundleLocator;
import org.hibernate.validator.spi.resourceloading.ResourceBundleLocator;
import org.springframework.lang.Nullable;

import java.util.Locale;
import java.util.Optional;
import java.util.ResourceBundle;

/**
 * 扩展资源加载
 * <p>获取资源时，优先从before中获取，没有则取after中获取</p>
 *
 * @author LiuYang
 * @since 2020/9/22
 * @version 1.0.0
 */
public class ExtensionsResourceBundleLocator extends DelegatingResourceBundleLocator {
    @Nullable
    private final ResourceBundleLocator before;

    /**
     * <p>Constructor for ExtensionsResourceBundleLocator.</p>
     *
     * @param before a {@link org.hibernate.validator.spi.resourceloading.ResourceBundleLocator} object.
     * @param after a {@link org.hibernate.validator.spi.resourceloading.ResourceBundleLocator} object.
     */
    public ExtensionsResourceBundleLocator(@Nullable ResourceBundleLocator before, @Nullable ResourceBundleLocator after) {
        super(after);
        this.before = before;
    }

    /** {@inheritDoc} */
    @Override
    public ResourceBundle getResourceBundle(Locale locale) {
        return Optional.ofNullable(before)
                .map(t -> t.getResourceBundle(locale))
                .orElseGet(() -> super.getResourceBundle(locale));
    }
}
